package com.runyu.cordova.plugin.zebra.barcode;

import android.app.Activity;

import com.runyu.cordova.plugin.DeviceManager;
import com.symbol.emdk.EMDKManager;
import com.symbol.emdk.EMDKResults;

import org.apache.cordova.CordovaInterface;
import org.apache.cordova.LOG;

import java.util.ArrayList;
import java.util.List;

public class ZebraBarcodeManager {
	private final String TAG = "ZebraBarcodeManager";
	private final List<EMDKManagerCreatedListener> emdkManagerCreatedListeners = new ArrayList<>();

	private EMDKManager emdkManager;

	private static final ZebraBarcodeManager instance;

	private ZebraBarcodeManager() {

	}

	static {
		instance = new ZebraBarcodeManager();
	}

	public static ZebraBarcodeManager getInstance() {
		return instance;
	}

	public void init(CordovaInterface cordovaInterface) {
		Activity activity = cordovaInterface.getActivity();
		EMDKResults result = EMDKManager.getEMDKManager(activity.getApplicationContext(), new EMDKManager.EMDKListener() {

			@Override
			public void onOpened(EMDKManager emdkManager) {
				doInit(emdkManager);
			}

			@Override
			public void onClosed() {
				//TODO
				LOG.e(TAG, "onClosed");
				if (emdkManager != null) {
					emdkManager.release();
					emdkManager = null;
				}

			}
		});
		LOG.i(TAG, "onOpened",result.statusCode);
	}

	private void doInit(EMDKManager emdkManager) {
		this.emdkManager = emdkManager;
		synchronized (ZebraBarcodeManager.this.emdkManagerCreatedListeners) {
			for (EMDKManagerCreatedListener emdkManagerCreatedListener : emdkManagerCreatedListeners) {
				emdkManagerCreatedListener.onCreated(this.emdkManager);
			}
		}
	}



	public void registerEmdkCreatedListener(EMDKManagerCreatedListener emdkCreatedListener) {
		if (this.emdkManager != null) {
			emdkCreatedListener.onCreated(this.emdkManager);
			return;
		}
		synchronized (this.emdkManagerCreatedListeners) {
			if (this.emdkManager != null) {
				emdkCreatedListener.onCreated(this.emdkManager);
				return;
			}
			this.emdkManagerCreatedListeners.add(emdkCreatedListener);
		}
	}
}
